package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Role;
import cn.wolfcode.rbac.mapper.RoleMapper;
import cn.wolfcode.rbac.query.PageResult;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@Transactional
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper mapper;
    @Override
    @Transactional(readOnly = true)
    public List<Role> list() {
        return mapper.selectAll();
    }

    @Override
    @Transactional(readOnly = true)
    public Role get(Long id) {
        return mapper.get(id);
    }

    @Override
    public void delete(Long id) {
        mapper.delete(id);
        //删除关系表
        mapper.deleteRelation(id);
    }

    @Override
    public void saveOrUpdate(Role role,Long [] ids) {
        if(role.getId() == null){
            //添加
            mapper.insert(role);
        }else{
            //更新
            mapper.update(role);
            mapper.deleteRelation(role.getId());
        }
        if((ids != null)&& (ids.length > 0)){
            for (Long pid : ids){
                mapper.insertRelation(role.getId(),pid);
            }
        }
    }

    @Override
    @Transactional(readOnly = true)
    public PageInfo query(QueryObject qo) {
//        Integer rows = Integer.valueOf(mapper.selectForCount(qo));
//        if(rows.intValue() == 0){
//            return new PageResult(Integer.valueOf(qo.getPageSize()));
//        }
//        List<Role> list = mapper.selectForList(qo);
//        return new PageResult(Integer.valueOf(qo.getCurrentPage()),rows,list,Integer.valueOf(qo.getPageSize()));
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Role> list = mapper.selectForList(qo);
        return new PageInfo(list);
    }
}
